<?php
//结算

namespace app\index\controller;
use app\common\Base;
use app\common\Upload;
use app\index\model\Business;
use app\index\model\Carts;
use app\index\model\CouponReceive;
use app\index\model\Money;
use app\index\model\Order;
use app\index\model\OrderCommodity;
use app\index\model\User;
use app\index\model\UserAddress;
use app\index\validate\SettlementValidator;
use Endroid\QrCode\ErrorCorrectionLevel;
use Jenssegers\Agent\Agent;
use think\cache\driver\Redis;
use think\facade\Env;
use think\Exception;
use think\Request;
use Endroid\QrCode\QrCode;
use function AlibabaCloud\Client\block;

class Settlement extends  Base
{

    //列出收获地址 成功
    /**
     * @param UserAddress $userAddress
     * @return \think\response\Json
     * @throws Exception
     */
    public  function  selAddress( Request $request,UserAddress $userAddress){
        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $uId = $arr['id'];//获取用户id

        try{
            if ($userAddress->selAddress($uId)){
                return  responseJson(Base::OK,'列出成功',$userAddress->selAddress($uId));
            }else{
                return  responseJson(Base::FAIL,'服务器错误');
            }
            // TODO 若上if为false，那么前端是没有任何数据接收到？
        }catch (Exception $e){
            throw  $e;
        }
    }

    //去支付(存订单去数据库) 成功
//修改优惠劵状态
    /**
     * @param Request $request
     * @param Order $order
     * @param OrderCommodity $orderCommodity
     * @param SettlementValidator $SettlementValidator
     * @return \think\response\Json
     * @throws Exception
     */
        public function  addOrder( Request $request,CouponReceive $couponReceive, Order $order ,OrderCommodity $orderCommodity ){
            // TODO 将获取缓存信息放在中间件里
            $arr = $request->cacheInfo;
            $uid = $arr['id'];//获取用户id




            $businessid = $request ->post('businessid');//获取商家id数组
            $moneyall =$request ->post('moneyall');
            $realTotalMoney = $request ->post('realTotalMoney');
            $arr = $request ->post();//获取所有不需要处理的数据

            $paytype = $request ->post('paytype');//获取支付方式
            $orderRemarks = $request ->post('orderRemarks');//获取备注

            $shop = $request->post('Shop');//获取订单信息
            $coupon = $request->post('Coupon');//获取优惠卷信息
            // TODO 已保证coupon必定有下标0？
            try{
                if ($coupon==''){
                } else
                    if($coupon[0]!=''){
                        for($qq=0;$qq<count($coupon);$qq++){
                            $couid = $coupon[$qq];
                            if(!$couponReceive->payOrder($uid,$couid)){
                                return responseJson(Base::FAIL,'使用失败');
                            };
                        }
                    }


                $orderid = array();
                for($b = 0;$b<count($businessid);$b++){
                    $bid = $businessid[$b];
                    //随机出id
                    $turbo= mt_rand(1,10);
                    $idarr =json_decode($order->selOrderid(),true)[0]['orderNum'];
                    $id = substr($idarr,2) + $turbo;
                    $id = 'er' . $id;
                    // TODO 代码缩进不规范，数据校验不应该放在业务代码循环内

                    if(!$order ->addOrder($id,$uid,$bid,$arr,$paytype,$orderRemarks,$moneyall,$realTotalMoney) ){
                        return  responseJson(Base::FAIL,'添加失败');
                    }

                    for($i = 0;$i<count($shop);$i ++){
                        $ctext = $shop[$i];
//                  循环添加多个商品
                        if($ctext['bid'] == $bid){
                            $cid = $ctext['commodityId'];
                            $commodityImg = $ctext['commodityImg'];
                            $commodityName= $ctext['commodityName'];
                            $commodityNum= $ctext['commodityNum'];
                            $money= $ctext['money'];
                            if(!$orderCommodity->addOC($id, $cid,$commodityName,$commodityNum,$money,$commodityImg)){
                                return responseJson(Base::FAIL);
                            } ;
                        }
                    }
                    array_push($orderid , $id);
                }
                return  responseJson(Base::JUMP_PAGE,'添加成功',$orderid);
            }catch (Exception $e){
                throw  $e;
            }

        }


        //个人订单页用的
    public function userSeltext(Request $request,Order $order,OrderCommodity $orderCommodity,Business $business){
        $arr = $request->cacheInfo;
        $uid = $arr['id'];//获取用户id

        $orderid=$request->post('orderid');

        if(!$ordertext = json_decode($order->selOrder('orderNum',$orderid,'orderNum,businessId,payType,userName,userPhone,provide,city,county,street,detail,realTotalMoney,orderRemarks,createTime'),true)){
            return responseJson(Base::FAIL,'服务器错误');
        }
        if(!$ctext = json_decode($orderCommodity->selOC('orderId',$orderid,'commodityImg,commodityName,commodityNum,money,cid'),true)){
            return responseJson(Base::FAIL,'服务器错误');
        }
        $data['order']=$ordertext;
        $data['shop']=$ctext;

        for ($q = 0;$q<count($ctext) ;$q++){
            if(!$bname = json_decode($business->selb('id',$ordertext[0]['businessId'],'businessName'),true)){
                return responseJson(Base::FAIL,'服务器错误');
            }
            $data['shop'][$q]['bname']=$bname[0]['businessName'];
        }
        return responseJson(Base::JUMP_PAGE,'成功',$data);
    }
    /**
     * @param Request $request
     * @param Redis $redis
     * @param Order $order
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    //结算二维码（成功）
    public function  qrCode(Request $request , Redis $redis , Order $order){
        $orderId = $request -> post('orderId');//获取订单Id数组
        $paytype = $request -> post('paytype');//获取支付类型

        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $uid = $arr['id'];//获取用户id

        for($o=0;$o<count($orderId);$o++){
            if($order->selOrder("orderNum","$orderId[$o]",'businessId,realTotalMoney')){
                $ordertext = $order->selOrder("orderNum","$orderId[$o]",'businessId,realTotalMoney');//获取收款商家Id.获取订单价格
            }else{
                return responseJson(Base::FAIL,'错误，请重新下单');
            }
            // TODO $ordertext必定有数据？也必定会有下标0？
            $redisset = [
                'uid'=>$uid,
                'orderId'=>$orderId[$o],
                'businessId'=>$ordertext[0]['businessId'],
                'money'=>$ordertext[0]['realTotalMoney'],
                'paytype'=>$paytype
            ];
            
            app('mycache')->set($orderId[$o],json_encode($redisset),360);//信息存redis,3分钟之类完成，不然删除

        }
        //将多个订单num，拼接
        $ordernum = implode(',',$orderId);

        // TODO 地址栏拼接参数是用';'？
        $value = "http://dainty.wistudy.xyz/pages/payMent.html?token=".$_SERVER['HTTP_TOKEN']."&orderId=".$ordernum; //二维码内容 网址加订单id
        $qrCode  = new QrCode($value);
        $qrCode->setWriterByName('png');
        $qrCode->setSize(250);
        $qrCode->setMargin(5);
        $qrCode->setEncoding('utf-8');
        $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
        $qrCode->setForegroundColor(['r'=>0,'g'=>0,'b'=>0,'a'=>0,]);
        $qrCode->setBackgroundColor(['r'=>255,'g'=>255,'b'=>255,'a'=>0,]);
        $qrCode -> setWriterOptions(['exclude_xml_declaration'=>true]);

        $uploadname= $ordernum.  time() . 'qrcode.png'; //定义二维码文件名。

        // TODO 请使用框架定义好的常量获取runtime文件夹的路径
        $file= Env('RUNTIME_PATH').$uploadname;    //定义图片存放路径

        $fatherfile=Env('RUNTIME_PATH').DIRECTORY_SEPARATOR.'img';    //定义图片存放文件夹

        if(!is_dir($fatherfile)){
            mkdir($fatherfile,0777,true);
        }else{
            chmod($fatherfile,0777);
        }

        $qrCode->writeFile($file);

        $qiniu='http://hungry.wistudy.xyz/' . $uploadname;
        $upload = new Upload();
        if ($upload->upload($file,$uploadname)){
            unlink($file);
            return responseJson(Base::JUMP_PAGE,'生成成功',$qiniu);
        }
        
        return  responseJson(Base::FAIL,'上传错误');


    }

    // 商品详情(成功）

    /**
     * @param Request $request
     * @param OrderCommodity $orderCommodity
     * @return \think\response\Json
     */
    public function comText(Request $request ,OrderCommodity $orderCommodity){

        $orderId = $request ->post('orderId');//获取订单信息
        $comtext =$orderCommodity ->selOC('orderId',$orderId,'commodityImg,commodityName,commodityNum,money');//查询订单商品信息
        return responseJson(Base::OK , '查询成功',$comtext);

    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws Exception
     */
   //移动端支付信息 (成功）
    public function  getPaytext(Request $request,Business $business,Order $order){
        $oId = $request -> post('order');//获取二维码传的地址上的订单ID


        $arrar = array();
        $Bid = array();
        $businessname = array();
        $money = 0;
        // TODO 代码缩进不规范
         try {
                for($o=0;$o<count($oId);$o++) {
                    $orderId = $oId[$o];
                    if (!$Data = app('mycache')->get($orderId)) {
                        return responseJson(Base::FAIL, '服务器出错，请重试');
                    }

                    $Data = json_decode($Data, true);

                    $bid = $Data['businessId'];
                    $paytype = $Data['paytype'];//支付类型

                    $businessName = $business->findBusiness($bid);
                    array_push($Bid, $bid);
                    $bid = implode(',',$Bid);
                    $Data['businessname'] = $businessName;
                    array_push($businessname, $businessName);
                    $businessName = implode(',',$businessname);
                    $money += $Data['money'];//总价
                }
                if ($paytype == 0){
                    $paytext = 'MicroMessenger';
                }else{
                    $paytext = 'AlipayClient';
                }
             $agent = new Agent();
                 if (strpos($_SERVER['HTTP_USER_AGENT'], $paytext) !== false ) {
                     $ordernum = implode(',',$oId); 
                     $arrar["uid"] = $Data['uid'];
                     $arrar["orderId"] = $ordernum;
                     $arrar["businessId"] = $bid;
                     $arrar["money"] = $money;
                     $arrar["businessname"] = $businessName;
                     $arrar["agent"] = $_SERVER['HTTP_USER_AGENT'];
                     for($n=0;$n<count($oId);$n++){
                         $odid = $oId[$n];
                         if(!$order->udqcd($odid)){
                             return  responseJson(Base::FAIL,'错误了哦');
                         }
                     }
                     return responseJson(Base::OK, '列出成功', $arrar);
                 }
                   
                   return responseJson(Base::FAIL,'请使用正确的软件进行支付');
            } catch (Exception $e) {
                throw  $e;
         }

    }

    public  function  Bigbug(Request $request,Order $order){
        $arr = $request->cacheInfo;
        $userId = $arr['id'];//获取用户id
        $orderid = $request->post('order');
        $type = 0;
        for($i=0;$i<count($orderid);$i++){
            $ordertext =json_decode($order->appFindIdInfo($userId,$orderid[$i]),true);
//            print_r($ordertext);
            $ordertype = $ordertext[0]['orderStatus'];
            if($ordertype == -4){
                $type = 1;
            }
        }
        if($type == 1){
            return responseJson(Base::OK,'以扫码',$type);
        }
        return responseJson(Base::FAIL,'未扫码',$type);

    }

    /**
     * @param Request $request
     * @param User $user
     * @param Money $money
     * @param Order $order
     * @param Business $business
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    //支付 (成功）
    public  function  pay(Request $request ,User $user,Money $money,Order $order,Business $business  ){

        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $uId = $arr['id'];//获取用户id
        try{


    //        $paypassword =md5(md5($request -> post('paypassword')).$user->selUsertext('id',$uId,'salt'));//获取支付密码
            $paypassword =md5($request -> post('paypassword'));
            $orderId =$request -> post('orderId') ;//获取订单ID数组

            $businessname = array();
            $getmoney = 0;

            for($o=0;$o<count($orderId);$o++) {
                if(!$array = json_decode(app('mycache')->get( $orderId[$o]),true)){
                    return responseJson(Base::FAIL, '超时，请重试');
                }
                $paymoney  =$array['money'];//订单价格
                $Time = time();
                $updataTime =date("Y-m-d H:i:s",$Time);
                $businessId  =$array['businessId'];//商家id

                $businessName =$business->findBusiness($businessId);//获取商家名3

                //判断现登入用户是否和支付账号相符
                if (!$array['uid'] == $uId) {
                    return responseJson(Base::FAIL, '服务器出错，请重试');
                }

                //判断获取用户余额
                if (!$money->selMoneytext($uId)) {
                    return responseJson(Base::FAIL, '用户未充值，请充值');
                }
                $userbalance = $money->selMoneytext($uId)[0]['Money'];
                //判断获取商家余额



                if (!json_decode($money->selMoneytext($uId),true)[0]['Money']) {
                    return responseJson(Base::FAIL, '商家未充值，请充值');
                }

                $businessbalance = json_decode($money->selMoneytext($uId),true)[0]['Money'];
                //判断订单状态是不是待付款
//
                if ($order->selOrder('orderNum', $orderId[$o], 'orderStatus')[0]['orderStatus'] != -4) {
                    return responseJson(Base::FAIL, '获取订单失败，请重试（订单状态不是待付款）');
                }

                //判断支付密码是否正确
                if (json_decode($user->selUsertext('id', $uId, 'payPassword'),true)[0]['payPassword'] != $paypassword) {
                    return responseJson(Base::FAIL, '支付失败，请重试（密码）');
                }

                //判断余额是否充足
                if ($userbalance < $paymoney) {
                    return responseJson(Base::FAIL, '支付失败，请重试（余额）');
                }

                //进行交易
                if (!$money->payMoney($uId, $paymoney, $businessId, $userbalance, $businessbalance)) {
                    return responseJson(Base::FAIL, '支付失败，请重试（服务器）');
                }
                $order->payOrder($orderId[$o]);


                array_push($businessname, $businessName);
                $bName = implode(',',$businessname);
                $getmoney += $paymoney;//总价
            }
            $orderid = implode(',',$orderId);
            $paytextarr = [$bName, $getmoney, $updataTime, $orderid];
            return responseJson(Base::OK,'支付成功',$paytextarr);
        }catch (Exception $e){
                throw  $e;
        }
    }

    public function delCarts(Request $request,Carts $carts){
        $arr = $request->cacheInfo;
        $uId = $arr['id'];//获取用户id
        $cartstext = $request->post('array');

        try{
            for ($i=0;$i<count($cartstext);$i++){
                $comid = $cartstext[$i];
                if(!$carts->cartsdel($uId,$comid)){
                    return responseJson(Base::FAIL,'失败');
                }

            }
            return responseJson(Base::OK,'成功');

        }catch (Exception $e){
            throw  $e;
        }

    }

    
    //支付状态(成功）

    /**
     * @param Request $request
     * @param Order $order
     * @return \think\response\Json
     */
     public function  payState(Request $request , Order $order){
         $money = 0;
         $ordertext = $request->post('orderId');
         for($o=0;$o<count($ordertext);$o++) {
             $orderId = $ordertext[$o];
             $arr = $order->selOrder('orderNum', $orderId, 'orderStatus , realTotalMoney');
             if ($arr[0]['orderStatus'] != '-1') {
                 return responseJson(Base::FAIL, '支付失败，请重试');
             }
             $realTotalMoney = $arr[0]['realTotalMoney'];
             $money +=$realTotalMoney;
         }
         return responseJson(Base::OK,'支付成功',$money);
     }

}